<template>
  <div class="cesium">
    <div class="cesiumContainer2" ref="cesiumContainer"></div>
    <Compass 
      style="position:absolute;right:30px;top:15px;z-index: 99;" 
      :viewer="viewer" 
      compassId="RoutePlanMapCompass"
      ref="compass" 
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, getCurrentInstance } from 'vue'
import * as anime from 'animejs'
import { v4 as uuidv4 } from 'uuid'
import Compass from './ToolsCompass.vue'
import { InitBaseMap, showPolygon } from "../assets/cesiumFunction/Map"
import { ShowStatus } from '../assets/cesiumFunction/SmartView'
import { lineLayerName, uavLayerName, groundLayerName, ugLineLayerName, uavConnectLayerName, areaLayerName } from "../assets/cesiumFunction/LayerName"
import { addDrone, addGround } from "../assets/cesiumFunction/Map"
import { searchPlanById } from "../api/RoutePlan"

const props = defineProps(['showToolBox'])
const emit = defineEmits(['update:showToolBox'])

const instance = getCurrentInstance()

// 响应式数据
const cesiumContainer = ref()
const compass = ref()
const viewer = ref(null)
const showStatus = ref(null)
const tracker = ref(null)
const showLayerManager = ref(true)
const showAlarmManager = ref(true)

// 绘制无人机的实时状态
const uavStatus = () => {
  const terrainMapUrl = window.SystemConfig.terrainMapUrl
  let terrainMap = null
  if (terrainMapUrl !== '') {
    terrainMap = new Cesium.CesiumTerrainProvider({
      url: `${terrainMapUrl}`,
      requestWaterMask: true,
      requestVertexNormals: false,
    })
    viewer.value.terrainProvider = terrainMap
  }

  const uavModelUri = null
  showStatus.value = new ShowStatus(viewer.value,
    uavModelUri, 90, "uav_status",
    "uav_sn", "uav_lng", "uav_lat", "uav_ground_height", "uav_heading",
    "camera_azimuth", "camera_pitch", 
    "camera_fieldofview", "aspect")
}

// 初始化地图
const initialGlobeView = () => {
  const viewerInstance = InitBaseMap(cesiumContainer.value)
  window.viewer = viewerInstance
  viewer.value = viewerInstance
  
  const terrainMapUrl = window.SystemConfig.terrainMapUrl
  let terrainMap = null
  if (terrainMapUrl !== '') {
    terrainMap = new Cesium.CesiumTerrainProvider({
      url: `${terrainMapUrl}`,
      requestWaterMask: true,
      requestVertexNormals: false,
    })
    viewer.value.terrainProvider = terrainMap
  }
}

// 初始化绘制助手
const initDrawHelper = () => {
  tracker.value = new GlobeTracker(viewer.value)
}

// 清空实体图层
const clearEntityLayer = (layerName) => {
  if (viewer.value) {
    const entities = viewer.value.entities.values
    for (let i = entities.length - 1; i >= 0; i--) {
      const entity = entities[i]
      if (entity.layerId === layerName) {
        viewer.value.entities.remove(entity)
      }
    }
  }
}

// 显示右侧抽屉
const showRightDrawer = () => {
  if (showLayerManager.value) {
    anime({
      targets: '.rightDrawer',
      right: '-300px',
    })
  } else {
    anime({
      targets: '.rightDrawer',
      right: '10px',
      easing: 'easeInOutQuad'
    })
  }
  showLayerManager.value = !showLayerManager.value
}

// 显示右下角抽屉
const showrightBottomDrawerContent = () => {
  if (showAlarmManager.value) {
    anime({
      targets: '.rightBottomDrawer',
      right: '-300px',
    })
  } else {
    anime({
      targets: '.rightBottomDrawer',
      right: '10px',
      easing: 'easeInOutQuad'
    })
  }
  showAlarmManager.value = !showAlarmManager.value
}

// 监听禁飞区变化
watch(() => instance.proxy.$store?.state?.wsEvent?.noFlyZoneCreate, () => {
  if (instance.proxy.$store?.state?.wsEvent?.noFlyZoneCreate) {
    clearEntityLayer('noFlyZoneLayer')
  }
})

watch(() => instance.proxy.$store?.state?.wsEvent?.noFlyZoneUpdate, () => {
  if (instance.proxy.$store?.state?.wsEvent?.noFlyZoneUpdate) {
    clearEntityLayer('noFlyZoneLayer')
  }
})

watch(() => instance.proxy.$store?.state?.wsEvent?.noFlyZoneDelete, () => {
  if (instance.proxy.$store?.state?.wsEvent?.noFlyZoneDelete) {
    clearEntityLayer('noFlyZoneLayer')
  }
})

// 监听无人机设备信息
watch(() => instance.proxy.$store?.state?.DeviceInfo, (deviceInfo) => {
  if (showStatus.value == null) return
  
  console.log("无人机实时数据", deviceInfo)
  if (typeof (deviceInfo.flyBaseState.longitude) === "number" && typeof (deviceInfo.flyBaseState.latitude) === "number") {
    const data = {
      "uav_sn": deviceInfo.deviceSn,
      "uav_lng": deviceInfo.flyBaseState.longitude,
      "uav_lat": deviceInfo.flyBaseState.latitude,
      "uav_ground_height": deviceInfo.flyBaseState.altitude,
      "uav_heading": deviceInfo.flyBaseState.uav_head,
      "uav_pitch": deviceInfo.flyBaseState.uav_pitch,
      "uav_roll": deviceInfo.flyBaseState.uav_roll,
      "camera_azimuth": deviceInfo.payloadState.payload_head,
      "camera_pitch": deviceInfo.payloadState.payload_pitch,
      "camera_roll": deviceInfo.payloadState.payload_roll,
      "camera_fieldofview": deviceInfo.cameraState.field_angle,
      "uav_status": deviceInfo.flyControlState.flight_status,
      "aspect": 1.75,
    }
    console.log("showStatus接收数据", deviceInfo)
    showStatus.value.AddData(data)
  }
})

// 生命周期钩子
onMounted(() => {
  initialGlobeView()
  initDrawHelper()
  uavStatus()
})

onUnmounted(() => {
  if (viewer.value) {
    viewer.value.destroy()
  }
})

// 暴露给父组件的方法
defineExpose({
  viewer,
  tracker,
  clearEntityLayer,
  showRightDrawer,
  showrightBottomDrawerContent
})
</script>

<style scoped>
.cesium {
  width: 100%;
  height: 100%;
  position: relative;
}

.cesiumContainer2 {
  width: 100%;
  height: 100%;
}
</style>